package cn.xuexiluxian.open.admin.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.system.model.entity.SystemRole;
import cn.xuexiluxian.open.system.model.entity.SystemUnit;
import cn.xuexiluxian.open.system.model.entity.SystemUserRole;
import cn.xuexiluxian.open.system.service.ISystemRoleService;
import cn.xuexiluxian.open.system.service.ISystemUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.system.model.dto.SystemUserDTO;
import cn.xuexiluxian.open.system.model.entity.SystemUser;
import cn.xuexiluxian.open.system.model.req.SystemUserREQ;
import cn.xuexiluxian.open.system.service.ISystemUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */
@Slf4j
@RestController
@RequestMapping("system/user")
public class SystemUserController {
    @Autowired
    private ISystemUserService systemUserService;
    @Autowired
    private ISystemRoleService systemRoleService;
    @Autowired
    private ISystemUserRoleService systemUserRoleService;

    /**
     * 分页查询用户
     * @param page
     * @param params
     * @return
     */
    @GetMapping(value = "page")
    @Log(title = "用户管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:user:page')")
    public ResponseResult page(Page page, SystemUserREQ params) {
        Page<SystemUser> pageList = systemUserService.pageList(page, params);
        return ResponseResult.ok(pageList);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RepeatSubmit
    @GetMapping("delete/{id}")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('system:user:delete')")
    public ResponseResult delete(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }

        SystemUser user = systemUserService.getById(id);
        // 如果为系统内置用户，则不允许删除
        if(user.getSystemed() == 1){
            return ResponseResult.error(ResultStatusCodeEnum.BUILT_IN_DATA_NODELETE);
        }

        boolean b = systemUserService.delete(id);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 用户详情
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Log(title = "用户管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:user:get')")
    public ResponseResult get(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        Map<String, Object> result = systemUserService.detail(id);
        if(result != null){
            return ResponseResult.ok(result);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    /**
     * 添加用户
     * @param systemUserDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@permission.hasPermission('system:user:add')")
    public ResponseResult add(@RequestBody SystemUserDTO systemUserDTO){
        if(systemUserDTO == null || StrUtil.isBlank(systemUserDTO.getPassword())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        if(StrUtil.isBlank(systemUserDTO.getUsername())){
            return ResponseResult.error(ResultStatusCodeEnum.USERNAME_NOT_SET);
        }
        if(StrUtil.isBlank(systemUserDTO.getPhone())){
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }

        SystemUser temp = systemUserService.selectOneByUserName(systemUserDTO.getUsername());
        if(temp != null){
            return ResponseResult.error(ResultStatusCodeEnum.USER_EXIST);
        }
        temp = systemUserService.selectOneByMobile(systemUserDTO.getPhone());
        if(temp != null){
            return ResponseResult.error(ResultStatusCodeEnum.USER_EXIST);
        }

        boolean b = systemUserService.saveBean(systemUserDTO);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改用户
     * @param systemUserDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("update")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@permission.hasPermission('system:user:update')")
    public ResponseResult update(@RequestBody SystemUserDTO systemUserDTO){
        if(systemUserDTO == null || StrUtil.isBlank(systemUserDTO.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemUser user = systemUserService.getById(systemUserDTO.getId());
        // 如果为系统内置用户，则不允许修改
        if(user.getSystemed() == 1){
            return ResponseResult.error(ResultStatusCodeEnum.BUILT_IN_DATA_NOUPDATE);
        }
        boolean b = systemUserService.updateBean(systemUserDTO);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    @GetMapping("reset/{id}")
    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @PreAuthorize("@permission.hasPermission('system:user:reset')")
    public ResponseResult reset(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        boolean b = systemUserService.reset(id);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 查询所有角色和当前选中的角色
     * @param id
     * @return
     */
    @GetMapping("checked/{id}")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PreAuthorize("@permission.hasPermission('system:user:grant')")
    public ResponseResult checked(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        LambdaQueryWrapper<SystemRole> queryWrapper = Wrappers.<SystemRole>lambdaQuery()
                .eq(true, SystemRole::getEnabled, 1);
        List<SystemRole> roles = systemRoleService.list(queryWrapper);

        List<String> checkedRoleIds = systemUserRoleService.selectCheckedByUserId(id);

        Map<String, Object> result = new HashMap<>();
        result.put("roles", roles);
        result.put("checkedRoleIds", checkedRoleIds);

        return ResponseResult.ok(result);
    }

    /**
     * 授权角色
     * @param list
     * @return
     */
    @RepeatSubmit
    @PostMapping("grant")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PreAuthorize("@permission.hasPermission('system:user:grant')")
    public ResponseResult grant(@RequestBody List<SystemUserRole> list){
        if(list == null || list.size() <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        boolean b = systemUserService.grant(list);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }
}
